from sqlalchemy import Column, Integer, Text, ForeignKeyConstraint, ForeignKey, Float, String

from sqlalchemy.ext.declarative import declarative_base

from sqlalchemy.orm import (
    scoped_session,
    sessionmaker,
    relationship,
    )

from zope.sqlalchemy import ZopeTransactionExtension

DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()

class Keys(Base):
    __tablename__ = 'keys'
    key = Column(Text, primary_key=True)
    
    def __init__(self, key):
        self.key = key
    
class Data(Base):
    __tablename__ = 'data'
    __table_args__ = (
            ForeignKeyConstraint(['key'], ['keys.key']),
            )
    id = Column(Integer, autoincrement=True, primary_key=True)
    key = Column(Text, ForeignKey('keys.key'), nullable=False)
    close = Column(Float)
    date = Column(String)
    keys = relationship(Keys, primaryjoin=key == Keys.key)
    
    def __init__(self, key, close, date):
        self.key = key
        self.close = close
        self.date = date

class MyModel(Base):
    __tablename__ = 'models'
    id = Column(Integer, primary_key=True)
    name = Column(Text, unique=True)
    value = Column(Integer)

    def __init__(self, name, value):
        self.name = name
        self.value = value
